<template>
	<view style="height: 100%;" class="pd-t-md">
		<MyTab2 class="tab round-tab bk-white-gray" :items="rounds" :onChange="onRankTypeChange"></MyTab2>
		<view class="score-tb">
			<MyTable :columns="columns" :rows="rows" :headerStyle="headerStyle" :bodyStyle="bodyStyle" :rowStyle="rowStyle" :onTapRow="onTapRow" :onTapBtn="onTapBtn" @tapBtnEvent="tapBtnEvent"></MyTable>
		</view>

		<view class="cu-modal" :class="showModal?'show':''">
			<view class="cu-dialog" v-if="showWeightModal">
				<view style="display: flex;justify-content: center; align-items: center; margin: 50rpx 0rpx; font-size: large; font-weight: bold;">
					<text class="selectModal">增加数据</text>/<text @click="showWeightModal=false">罚分</text>
				</view>
				<view>
					<view style="display: flex; justify-content: space-around; align-items: center; margin: 30rpx 0rpx;">
						<view style="width:150upx">重量：</view>
						<input style="width:400upx" inputmode="decimal" pattern="-?\d*\.?\d*" v-model="modifyWeight" placeholder="请输入修改后的重量"></input>
					</view>
					<view style="display: flex; justify-content: space-around; align-items: center; margin: 30rpx 0rpx;">
						<view style="width:150upx">条数：</view>
						<input style="width:400upx" v-model="modifyNumber" placeholder="请输入修改后的条数"></input>
					</view>
					
					<view style="display: flex; justify-content: space-around; align-items: center; margin: 50rpx 0rpx;">
						<button style="width: 200rpx; padding: 10rpx 0rpx; background-color: #E93323; color: white;" @click="hideModal">取消</button>
						<button style="width: 200rpx; padding: 10rpx 0rpx; background-color: #E93323; color: white;" @click="doModifyRace">确定</button>
					</view>
				</view>
			</view>
			<view class="cu-dialog" v-else >
				<view style="display: flex;justify-content: center; align-items: center; margin: 50rpx 0rpx; font-size: large; font-weight: bold;">
					<text @click="showWeightModal=true">增加数据</text>/<text class="selectModal">罚分</text>
				</view>
				<view>
					<view style="display: flex; justify-content: space-around; align-items: center; margin: 30rpx 0rpx;">
						<view style="width:150upx">罚分：</view>
						<input style="width:400upx" v-model="deductPoints" placeholder="请输入罚分"></input>
					</view>
					
					<view style="display: flex; justify-content: space-around; align-items: center; margin: 50rpx 0rpx;">
						<button style="width: 200rpx; padding: 10rpx 0rpx; background-color: #E93323; color: white;" @click="hideModal">取消</button>
						<button style="width: 200rpx; padding: 10rpx 0rpx; background-color: #E93323; color: white;" @click="doDeductPoints">确定</button>
					</view>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import MyTab2 from '@/components/my/MyTab2.vue';
	import MyTable from '@/components/my/MyTable.vue';
	
	import {
		getRaceById,
		raceDeductPoints,
		raceModifyRace
	} from '@/api/fsh.js';
	
	import { Modal } from '../../libs/uniApi.js';
	import {MyTip} from '@/components/ssty/common.js';
	
	const app = getApp();
	
	export default {
		components: {
			MyTab2,
			MyTable
		},
		
		data() {
			return {
				rounds: [
				],
				
				headerStyle: {
					'height': '80rpx', // $round-tab-h
					'background-color': '#FFF',
					'border-bottom': '1px solid #f8f8f8',
					'font-weight': 'bold'
				},
				bodyStyle: {
					'background-color': '#FFF',
				},
				rowStyle: {
					'height': '72rpx'
				},
				
				columns: [
				],
				rows: [],

				showModal: false,
				showWeightModal: true,
				deductPoints: '',
				modifyWeight: '',
				modifyNumber: '',
				tabCurr: 0,
				tabSubCurr: 0,
			}
		},
		onLoad(options) {
			// this.rows = [];
			// for(let i = 0; i < 100; i++) {
			// 	let row = [];
			// 	for(let j = 0; j < this.columns.length; j++) {
			// 		row.push((i+1)+'-'+(j+1));
			// 	}
			// 	this.rows.push(row)
			// }
			this.for_raceMangeEditScore = options.for_raceMangeEditScore;
			this.raceId = parseInt(options.raceId);
			
			this.rowStyle = {
				'height': this.for_raceMangeEditScore?'72rpx':'60rpx'
			};
			
			console.log("race_score onLoad, options:", options, this);
		},
		onShow() {
			this.reloadData();
		},
		methods: {
			validateInput(input) {
				console.log("input",input)
			    const value = input.detail.value;
			
			    // 使用正则表达式定义允许输入的模式
			    const pattern = /^-?\d*\.?\d*$/;
			
			    // 如果输入不符合模式，则清除最后输入的字符
			    if (!pattern.test(value)) {
			        input.value = value.slice(0, -1);
			    }
			},
			reloadData() {
				getRaceById(this.raceId).then(res => {
					if(!res.entity.score) {
						Modal(this.for_raceMangeEditScore?'比赛开始后才能编辑成绩':'比赛开始后才能查询成绩', '', {
							showCancel: false
						}).then(() => {
							console.error("getRaceById result no score, navigateBack");
							uni.navigateBack();
						})
						return;
					}
					
					// 放在globalData中personal_score页面会使用
					app.globalData.race = res.entity.race;
					app.globalData.race_score = res.entity.score;
					
					let rounds = [];
					if(!this.for_raceMangeEditScore) {
						rounds = [{
							name: '总成绩',
							subCurr: 0,
							subItems: [
								{name: '综合'},
							]
						}];
					}
					let race = app.globalData.race;
					let partitions = JSON.parse(race.partitions);
					for(let i = 0; i < race.round_number; i++) {
						let round = {name: `第${i+1}场`, subCurr: 0, subItems:[]};
						for(let j = 0; j < partitions.length; j++)
							round.subItems.push({name: `分区${j+1}`})
						rounds.push(round);
					}
					this.rounds = rounds;
					
					this.onRankTypeChange(this.tabCurr, this.tabSubCurr);
				}).catch(err => {
					console.error("getRaceById fail, err=%o", err)
					this.$util.Tips({title: err.msg}, {tab: 3, url: 1}); // 提示并返回上一页面
				});
			},
			
			onRankTypeChange(curr, subcurr) {
				let race = app.globalData.race;
				let race_score = app.globalData.race_score;
				console.log(`onRankTypeChange, curr=${curr}, subcurr=${subcurr}`, "race:", race, "race_score:", race_score);

				this.tabCurr = curr;
				this.tabSubCurr = subcurr;

				const showAvatar = false; // 是否显示头像（暂时固定为false，以后有需要再放开）
				
				if(!this.for_raceMangeEditScore && curr == 0) {
					// ------ set table columns ------ 
					let avatarWidth = showAvatar ? 100 : 0;
					let min_width = 80;
					let width = parseInt((750-avatarWidth) / (race.round_number + 3));
					if(width < min_width)
						width = min_width;
					width = width + 'rpx';
					
					this.columns = [
						{name: "姓名", width: width}, 
						{name: "名次", width: width},
						{name: "总积分", width: width},
						{name: "总重量", width: width}
					];
					if(showAvatar)
						this.columns.unshift({name: "头像", width: avatarWidth+'rpx'});
					
					for(let i = 1; i <= race.round_number; i++)
						this.columns.push({name: "第"+i+"场", width: width});
					
					
					let playerTotalScore = race_score.filter(row=>row.round==0);
					playerTotalScore.sort(function(a,b){
						return a.score%1 - b.score%1
					});
					
					let rows = [];
					for(let i = 0; i < playerTotalScore.length; i++) {
						let item = playerTotalScore[i];
						let row = [];
						if(showAvatar)
							row.push(item.avatar);
						row.push(item.nickname);
						item.ranking = i+1;			// ranking
						row.push(item.ranking);     
						row.push(parseInt(item.score));
						row.push(item.totalRetWeight);
						// one round score
						for(let k = 1; k <= race.round_number; k++) {
							let a = race_score.filter(rs=>rs.user_id==item.user_id && rs.round==k );
							if(a.length > 0)
								row.push(parseInt(a[0].score));
							else
								row.push('--');
						}
						
						row.push(item.user_id); 
						
						rows.push(row);
					}
					
					this.rows = rows;
				}
				else {
				
					let scoreTypeByNum = parseInt(race_score[0].score_type) == 1;
					let scoreTitle = scoreTypeByNum?"条数":"重量";
					
					// ------ set table columns ------ 
					if(this.for_raceMangeEditScore) {
						this.columns = showAvatar ? [
							{name: "头像", width: '150rpx'},
							{name: "昵称", width: '120rpx'}, 
							{name: "钓位", width: '120rpx'},
							{name: scoreTitle, width: '120rpx'},
							{name: "积分", width: '150rpx'},
							{name: "罚分", width: '120rpx'},
							{name: "操作", width: '120rpx', btn: true},
						] : [
							{name: "昵称", width: '150rpx'}, 
							{name: "钓位", width: '150rpx'},
							{name: scoreTitle, width: '100rpx'},
							{name: "积分", width: '100rpx'},
							{name: "罚分", width: '100rpx'},
							{name: "操作", width: '150rpx', btn: true},
						];
					}
					else {
						this.columns = showAvatar ? [
							{name: "头像", width: '150rpx'},
							{name: "昵称", width: '120rpx'}, 
							{name: "钓位", width: '120rpx'},
							{name: scoreTitle, width: '120rpx'},
							{name: "积分", width: '150rpx'},
							{name: "罚分", width: '120rpx'},
						] : [
							{name: "昵称", width: '150rpx'}, 
							{name: "钓位", width: '150rpx'},
							{name: scoreTitle, width: '150rpx'},
							{name: "积分", width: '150rpx'},
							{name: "罚分", width: '150rpx'},
						];
					}
					// ------ set table rows ------ 
					let roundNo = this.for_raceMangeEditScore ? (curr + 1) : curr;
					let partitionNo = subcurr + 1;
					
					let playerRoundScore = race_score.filter(rs=>rs.race_partition==partitionNo && rs.round==roundNo);
					
					if(!this.for_raceMangeEditScore) {
						playerRoundScore.sort(function(a,b){
							return a.score%1 - b.score%1
						});
					}
					
					let rows = [];
					for(let i = 0; i < playerRoundScore.length; i++) {
						let item = playerRoundScore[i];
						let row = [];
						if(showAvatar)
							row.push(item.avatar);
						row.push(item.nickname);
						row.push(item.seat_no);
						row.push(scoreTypeByNum?item.ret_number:item.ret_weight);
						row.push(item.points< 0.01 ? '--' : item.points);
						row.push(item.deduct_points < 0.01 ? '--' : item.deduct_points);
						if(this.for_raceMangeEditScore)
							row.push("修改");
						row.push(item.user_id); 
						rows.push(row);
					}
					
					this.rows = rows;
				}
			},
			
			onTapRow(rowidx) {
				console.log("tap row "+rowidx, this.rows[rowidx])
				let userId = this.rows[rowidx][this.rows[rowidx].length-1];
				uni.navigateTo({
					url: `/pages/fsh_race/personal_score?userId=${userId}`
				})
			},

			onTapBtn(rowidx, colidx, btnTitle) {
				console.log("tap btn, row:"+rowidx+", col:"+colidx+", btn:"+btnTitle, this);
				//this.showModal = true;
				//this.deductPoints = this.rows[rowidx][4];
			},
			tapBtnEvent(rowidx, colidx, btnTitle) {
				console.log("tap btn, row:"+rowidx+", col:"+colidx+", btn:"+btnTitle, this);
				this.showModal = true;
				this.modifyWeight = 0;
				this.modifyNumber = 0;
				this.deductPoints = 0;
				this.deductPoints = parseFloat(this.rows[rowidx][4]);
				if(this.deductPoints < 0.01)
					this.deductPoints = '';
				this.__rowidx = rowidx;
			},
			// end
			
			hideModal() {
				this.showModal = false;
			},
			
			doModifyRace() {
				if(this.modifyWeight == null || isNaN(this.modifyWeight) || !this.modifyWeight)
					this.modifyWeight = 0;
				if(this.modifyNumber == null || isNaN(this.modifyNumber) || !this.modifyNumber)
					this.modifyNumber = 0;
				let w = parseFloat(this.modifyWeight).toFixed(2);
				let n = parseInt(this.modifyNumber);
				uni.showLoading({
					title: '提交修改重量中...',
					mask: true
				});
				
				let row = this.rows[this.__rowidx];
				raceModifyRace(this.raceId, this.tabCurr+1, this.tabSubCurr+1, row[row.length-1], w, n).then(res => {
					uni.hideLoading();
					console.log("raceModifyWeight",res)
					this.showModal = false;
					this.reloadData();
				}).catch(err => {
					uni.hideLoading();
					MyTip("提交数据失败："+err);
				})
			},
			
			doDeductPoints() {
				if(this.deductPoints == null || isNaN(this.deductPoints) || !this.deductPoints)
					this.deductPoints = 0;
				let f = parseFloat(this.deductPoints).toFixed(2);
				
				uni.showLoading({
					title: '提交罚分中...',
					mask: true
				});
				
				let row = this.rows[this.__rowidx];
				raceDeductPoints(this.raceId, this.tabCurr+1, this.tabSubCurr+1, row[row.length-1], f).then(res => {
					uni.hideLoading();
					this.showModal = false;
					this.reloadData();
				}).catch(err => {
					uni.hideLoading();
					MyTip("提交罚分失败："+err);
				})
				
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/leui.scss";
	
	page {
		height: 100vh;
		width: 100vw;
	}
	
	$roundTabHeight: 180rpx;
	
	.round-tab {
		height: $roundTabHeight;
	}
	.score-tb {
		width: 100%;
		height: calc(100vh - #{$roundTabHeight});
	}
	.selectModal {
		text-decoration:underline;
	}
</style>
